﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;
using BLL;
using DAL;

namespace WeChat.Common
{
    public class GetMedia
    {

        MediaBLL md = new MediaBLL();
        GetReturnJson gr = new GetReturnJson();
        /// <summary>
        /// 发送post请求获取永久素材列表,同步至数据库
        /// </summary>
        /// <param name="type">返回素材类型:图片（image）、视频（video）、语音 （voice）、图文（news）</param>
        /// <param name="offset">从第几个元素开始算</param>
        /// <param name="count">一共返回几个元素（取值1-20）</param>
        /// <returns>返回该类素材总数</returns>
        public int getMedia(string type,int offset,int count)
        {
            string accesstoken = GetAccess_token.getAccesstoken();
            string url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + accesstoken;

            string jsondata = "{\"type\":\"" + type + "\",\"offset\":\""+ offset +"\",\"count\":\"" + count + "\"}";
            string jsons = gr.postReturnJson(url, jsondata);

            DataTable dt = setDatatable();

            //判断返回值是否获取素材成功
            var js = new JavaScriptSerializer();
            var dc = js.Deserialize<Dictionary<string, object>>(jsons);
            if (dc.ContainsKey("errcode"))
            {
                ApplicationLog.Write("获取素材列表失败，errcode:" + dc["errcode"]);
                return 0;
            }
            else if (type.Equals("news"))//获取图文素材
            {
                JObject jo = JObject.Parse(jsons);
                JArray ja = JArray.Parse(jo["item"].ToString());
                //将图文素材循环出来保存至datatable中
                foreach (JToken jt in ja)
                {
                    string media_id = jt["media_id"].ToString();//素材id
                    string title = jt["content"]["news_item"][0]["title"].ToString();//素材标题
                    string updateTime = FormatTimeBLL.formatTime(jt["update_time"].ToString());
                    //将获取数据存入datatable中
                    dt.Rows.Add(new object[] { null, type, media_id, title, updateTime });
                }
                int i = md.updateMedia(dt, "Media");
                return Int32.Parse(jo["total_count"].ToString());
            }
            else//获取图片(image)、视频(video)、语音(voice)素材
            {
                JObject jo = JObject.Parse(jsons);
                JArray ja = JArray.Parse(jo["item"].ToString());

                foreach (JToken jt in ja)
                {
                    string media_id = jt["media_id"].ToString();
                    string name = jt["name"].ToString();
                    //DateTime updateTime = DateTime.Parse(jt["update_time"].ToString());
                    string updateTime = FormatTimeBLL.formatTime(jt["update_time"].ToString());
                    //将获取数据存入datatable中
                    dt.Rows.Add(new object[] { null, type, media_id, name, updateTime });
                }
                int m = md.updateMedia(dt, "Media");
                return Int32.Parse(jo["total_count"].ToString());
            }
            //return dt;
        }

        /// <summary>
        /// 删除素材
        /// </summary>
        /// <param name="media_id">素材ID</param>
        public string delMedia(string media_id)
        {
            string accesstoken = GetAccess_token.getAccesstoken();
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/material/del_material?access_token={0}", accesstoken);
            string jsondata = "{\"media_id\":\"" + media_id + "\"}";
            string returnJson = gr.postReturnJson(url, jsondata);
            var js = new JavaScriptSerializer();
            var dic = js.Deserialize<Dictionary<string, object>>(returnJson);
            if (dic["errcode"].ToString().Equals("0"))
            {
                //连接数据库删除素材
                md.delMedia(media_id);
                ApplicationLog.Write("删除素材成功！");
                return "删除素材成功!";
            }
            else
            {
                ApplicationLog.Write("删除素材失败！errcode" + dic["errcode"].ToString());
                return "删除素材失败!errcode:" + dic["errcode"].ToString();
            }
        }

        //新建一个表结构和media一样的datatable，并插入数据批量保存
        private DataTable setDatatable()
        {
            DataTable dt = new DataTable();
            DataColumn dc = dt.Columns.Add("id", Type.GetType("System.Int32"));
            dc.AutoIncrement = true;//自动增加
            dc.AutoIncrementSeed = 1;//起始为1
            dc.AutoIncrementStep = 1;//步长为1
            dc.AllowDBNull = false;
            
            dt.Columns.Add("type", Type.GetType("System.String"));
            dt.Columns.Add("media_id", Type.GetType("System.String"));
            dt.Columns.Add("title", Type.GetType("System.String"));
            dt.Columns.Add("update_time", Type.GetType("System.DateTime"));
            return dt;
        }
    }

}
